var app = getApp()
//常量数据配置
var ConstantData = require('../../../../common/constant_data.js')
var employerUtil = require('./employerUtil')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pcode: '',
    phonenum: '',
    VerifyCode: "获取验证码",
    loginBtnTxt: "登 录",
    loginBtnStatus: true,
    card_number: '',
    pt: '',
    authFlg:true,//true已授权添加,false未授权添加
    tipStatus:false,
    tipBtnName:'确认',
    leaseLimitFlg:true,//ture未达到当日上限，false已达上限
    dayMaxCount:0,
    leftLeaseCount:0,
    tipType:0,//0跳转到首页,1留在本页
    isStopDownSecond:false,//是否停止倒数秒数,false不停止,true停止
    hospitalName:'',//医院名称
    leaseList:[],
    numPerPage:10,
    pageNum:1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('opttt',options)
    var nophone = app.getUserLoginNoPhone();
    console.log("爱心租赁页面-----")
    console.log(nophone)
    if(nophone == null || nophone == undefined || nophone == 1) {
        wx.navigateTo({
          url: '../../../../pages/login/login?pt=outpatient_add_employer',
        }) 
    } 
    this.setData({
      isManage:options.isManage
    }) 
    getDataList(this)  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    wx.checkSession({
      success: function () {
        console.log("----------登录中")
        loginHandle(that, true);
      },
      fail: function () {
        //登录态过期      
        that.loginAuth('', '');
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this

    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/time_card_patient/is_auth_add_employer',
        header: header,
        success: function (res) {
          var flgData = res.data.data
          var authFlg = flgData.authFlg
          var leaseLimitFlg = flgData.leaseLimitFlg
          var dayMaxCount = flgData.dayMaxCount
          var leftLeaseCount = flgData.leftLeaseCount
          var hospitalName = flgData.hospitalName
          that.setData({
            authFlg: authFlg,
            leaseLimitFlg: leaseLimitFlg,
            dayMaxCount: dayMaxCount,
            leftLeaseCount: leftLeaseCount,
            hospitalName: hospitalName
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      tipStatus: false,
      isStopDownSecond:false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  setPcode: function (e) {
    this.data.pcode = e.detail.value;
  },
  setPhonenum: function (e) {
    this.data.phonenum = e.detail.value;
  },
  getPhoneCode: function () {
    var that = this
    console.log("---phonenum=" + this.data.phonenum)
    if (this.data.phonenum != '') {
      var total_micro_second = 60 * 1000;
      //验证码倒计时
      count_down(this, total_micro_second);
      console.log(ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/message/outpatient_bind')
      var phonenum = this.data.phonenum;

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/message/outpatient_bind',
          header: header,
          data: {
            phonenum: phonenum
          },
          success: function (res) {
            console.log("访问短信成功")
            console.log(res)
            var rst = res.data.result
            var desc = res.data.description
            if (rst != 0) {
              that.setData({
                tipStatus: true,
                tipContent: desc,
                tipBtnName: '确定',
                tipType: 1,//留在本页
                isStopDownSecond: true
              })
            }

          },
          fail: function (res) {
            console.log("发送短信失败")
            console.log(res)
          }
        })

      })
      
    } else {
      wx.showToast({
        title: '请输入手机号'
      })
    }
  },
  bindAgentLeaseShip: function () {
    if (!this.data.loginBtnStatus) {
      return;
    }

    var that = this
    if (this.data.pcode != '' && this.data.phonenum != '') {
      that.setData({
        loginBtnStatus: false
      })
      var total_micro_second = 30 * 1000;
      loginSecondCountDown(this, total_micro_second)
      var code = this.data.pcode;
      var phonenum = this.data.phonenum;
      this.addEmployer(phonenum, code);
    } else {
      wx.showToast({
        title: this.data.phonenum != '' ? '验证码为空' : '手机号为空',
      })
    }
  },
  addEmployer: function (phone, pcode) {
    var that = this;

    app.executeRequest(function (header) {

      //发起网络请求
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/time_card_patient/add_employer',
        header: header,
        data: {
          phone: phone,
          pcode: pcode
        },
        success: function (res) {
          var result = res.data.result;
          if (result == 0) {
            that.setData({
              loginBtnStatus: true,
              tipStatus: true,
              tipContent: '验证成功,到首页扫码即可为他(她)代租',
              tipBtnName: '确定'
            })
          } else {
            that.setData({
              loginBtnStatus: true
            })
            var desc = app.getResultDesc(res.data.description)
            wx.showToast({
              title: desc,
            })
          }
        }
      })

    })
    

  },
  /**
   * 弹框确认处理
   */
  tipBtnClick:function(){    
    if (this.data.tipType == 0) {
      wx.reLaunch({
        url: '../../../../pages/index/index',
      })
    }  
    this.setData({
      tipStatus: false,
      isStopDownSecond: false,
      tipType: 0
    })
  },
  loginAuth: function (phone, pcode) {
    var that = this;
    //调用登录接口
    wx.login({
      success: function (res) {
        console.log("wxLogin-------------")
        console.log(res);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/login',
            header:{
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'post',
            data: {
              code: res.code,
              phone: phone,
              pcode: pcode
            },
            success: function (res) {
              var result = res.data.result;
              if (result == 0) {
                try {
                  wx.setStorageSync('pass', res.data.data.pass);
                  wx.setStorageSync('temp', res.data.data.temp);
                  wx.setStorageSync('ltime', res.data.data.ltime);
                  wx.setStorageSync('cpass', res.data.data.cpass);
                  wx.setStorageSync('uuid', res.data.data.uuid);
                  wx.setStorageSync('nophone', res.data.data.nophone);
                  app.globalData.loginData = res.data.data;
                } catch (e) {
                }
                
                var nophone = res.data.data.nophone
                if(nophone == 1) {
                  wx.navigateTo({
                    url: '../../../../pages/login/login?pt=outpatient_add_employer',
                  }) 
                }
              } else {
                
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
          that.setData({
            alertBoxStatus: true,
            alertBoxTipContent: '登录失败',
            alertBoxBtnName: '确 定'
          })
        }
      }
    });
    // }
  },
  changePass: function () {
    var that = this;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/cpass',
        header: header,
        data: {
          cpass: wx.getStorageSync('cpass'),
          uuid: wx.getStorageSync('uuid'),
          oldPass: app.getUserLoginPass()
        },
        success: function (res) {
          if (res.data.result == 0) {
            wx.setStorageSync('pass', res.data.data.pass);
            wx.setStorageSync('temp', res.data.data.temp);
            wx.setStorageSync('ltime', res.data.data.ltime);
            app.globalData.loginData = res.data.data;
          } else {
            wx.navigateTo({
              url: '../../../../pages/login/login?pt=outpatient_add_employer'
            })
          }
        }
      })

    })

  
  },
  //触底加载下一页
  scrolltolower:function(){
    this.data.pageNum+1
    getDataList(this)
  },
  toManage:function(){
    wx.navigateTo({
      url: '../manage_careworker/manage_careworker',
    })
  },
  // 租赁明细
  toDetail:function(){
    wx.navigateTo({
      url: '../manage_detail/manage_detail?isManage='+this.data.isManage,
    })
  },
  // 扫码开锁跳转
  scanUnblanking:function(e){
    // wx.reLaunch({
    //   url: `/pages/index/index?pt=helpLeasing&helpUserPhone=${e.target.dataset.helpuserphone}`,
    // })
    employerUtil.scan(
      function(qrc){
        wx.navigateTo({
          url: '/pkgNew/pages/newConnectDev/index?qrc=' + escape(qrc) + '&type=helpLeasing'+'&helpUserPhone='+e.target.dataset.helpuserphone
        }) 
      }
    )
  }
})
//获取分页列表数据
function getDataList(that){
  that.setData({
    leaseList:that.data.leaseList.concat([{phone:125552526,leaseTime:'2023-10-02',leasePeriod:'12分钟',deviceNumber:5752,orderNo:5374584544},{}])
  })
}
//登录倒计时
function loginSecondCountDown(that, total_micro_second) {
  if (that.data.loginBtnStatus) {
    console.log("重新登录")
    return;
  }
  if (total_micro_second <= 0) {
    that.setData({
      loginBtnTxt: "重新登录"
    });
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    loginBtnTxt: "登录中,请稍后...(" + date_format(total_micro_second) + " 秒)"
  });

  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 1000;
    loginSecondCountDown(that, total_micro_second);
  }, 1000)
}

function count_down(that, total_micro_second) {
  if (that.data.isStopDownSecond) {
    that.setData({
      VerifyCode:'获取验证码'
    })
    return
  }
  if (total_micro_second <= 0) {
    that.setData({
      VerifyCode: "重新发送"
    });
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    VerifyCode: date_format(total_micro_second) + " 秒"
  });
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 1000;
    count_down(that, total_micro_second);
  }, 1000)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  return sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}


function loginHandle(that, passFlg) {
  try {
    var uuid = wx.getStorageSync('uuid');
    if (uuid) {
      if (passFlg) {
        that.changePass(); //更换令牌     
      }
      if (that.data.scanStatus) {
        return
      }
      that.setData({
        scanStatus: true,
        loginStatus: false
      })
    } else {
      that.loginAuth('', '')
    }
  } catch (e) {
  }
}